package com.dzsw.mustache;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * 渲染自定义对象
 */
public class AdvancedExample {

    public static void main(String[] args) throws IOException {
        // 创建 Mustache 工厂
        MustacheFactory mf = new DefaultMustacheFactory();
        // 编译一个包含自定义对象属性的模板
        Mustache mustache = mf.compile(new StringReader("Hello, {{person.name}}!"), "");
        // 创建一个 Person 对象
        Person person = new Person("Alice");
        // 用于写入模板输出的 StringWriter
        StringWriter writer = new StringWriter();
        // 执行模板与上下文
        mustache.execute(writer, new Context(person)).flush();
        // 输出结果
        System.out.println(writer.toString()); // 输出 Hello, Alice!
    }

    // 自定义对象 Person
    static class Person {
        String name;

        public Person(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    // 封装对象为上下文
    static class Context {
        Person person;

        public Context(Person person) {
            this.person = person;
        }

        public Person getPerson() {
            return person;
        }
    }
}
